import React, { useEffect, useState } from 'react';
import { Spin, Alert, Button } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import { qiankunHelpers } from '../../qiankun';
import './index.scss';

interface LoadingState {
  loading: boolean;
  error: boolean;
  errorMessage?: string;
}

const VueAppContainer: React.FC = () => {
  const [state, setState] = useState<LoadingState>({
    loading: true,
    error: false
  });

  const loadVueApp = async () => {
    setState({ loading: true, error: false });
    
    try {
      // 在组件挂载时加载Vue应用
      await qiankunHelpers.loadVueApp();
      
      // 监听微应用的加载状态
      const container = document.getElementById('vue3-container');
      if (container) {
        // 设置一个定时器来检查Vue应用是否成功加载
        const checkLoadTimeout = setTimeout(() => {
          // 如果10秒后容器内还没有内容，显示错误
          if (container.children.length === 0 || container.innerHTML.includes('Spin')) {
            setState({
              loading: false,
              error: true,
              errorMessage: 'Vue3微应用加载超时，请检查子应用是否正常运行在 http://localhost:8080'
            });
          } else {
            setState({ loading: false, error: false });
          }
        }, 10000);

        // 如果微应用成功加载，清除定时器
        const observer = new MutationObserver(() => {
          if (container.children.length > 0 && !container.innerHTML.includes('ant-spin')) {
            setState({ loading: false, error: false });
            clearTimeout(checkLoadTimeout);
            observer.disconnect();
          }
        });

        observer.observe(container, {
          childList: true,
          subtree: true
        });

        return () => {
          clearTimeout(checkLoadTimeout);
          observer.disconnect();
        };
      }
    } catch (error) {
      console.error('加载Vue应用失败:', error);
      setState({
        loading: false,
        error: true,
        errorMessage: '加载Vue3微应用失败，请确保子应用正在运行'
      });
    }
  };

  useEffect(() => {
    loadVueApp();

    return () => {
      // 组件卸载时，也卸载Vue应用
      qiankunHelpers.unloadVueApp();
    };
  }, []);

  const handleRetry = () => {
    loadVueApp();
  };

  const renderContent = () => {
    if (state.error) {
      return (
        <div className="vue-app-error">
          <Alert
            message="微应用加载失败"
            description={
              <div>
                <p>{state.errorMessage}</p>
                <p>请确保：</p>
                <ul>
                  <li>Vue3子应用已在 http://localhost:8080 端口启动</li>
                  <li>子应用已正确配置乾坤接入代码</li>
                  <li>网络连接正常</li>
                </ul>
              </div>
            }
            type="error"
            showIcon
            action={
              <Button 
                icon={<ReloadOutlined />} 
                onClick={handleRetry}
                type="primary"
              >
                重新加载
              </Button>
            }
          />
        </div>
      );
    }

    if (state.loading) {
      return (
        <div className="vue-app-loading">
          <Spin tip="正在加载Vue3微应用，请稍候..." size="large" />
          <p className="loading-hint">首次加载可能需要较长时间</p>
        </div>
      );
    }

    return null;
  };

  return (
    <div className="vue-app-wrapper">
      <h2 className="vue-app-title">Vue 3 微应用</h2>
      {/* 这个div将作为Vue应用的挂载点 */}
      <div id="vue3-container" className="vue-app-container">
        {renderContent()}
      </div>
    </div>
  );
};

export default VueAppContainer;